package com.company.cloud.goodsrestservice.web;

import com.company.cloud.goodsrestservice.core.Result;
import com.company.cloud.goodsrestservice.core.ResultGenerator;
import com.company.cloud.goodsrestservice.model.Goods;
import com.company.cloud.goodsrestservice.model.GoodsPictureRel;
import com.company.cloud.goodsrestservice.model.Picture;
import com.company.cloud.goodsrestservice.service.GoodsPictureRelService;
import com.company.cloud.goodsrestservice.service.GoodsService;
import com.company.cloud.goodsrestservice.service.PictureService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.List;

/**
 * Created by reabout on 2018/04/02.
 */
@RestController
@RequestMapping("/picture")
public class PictureController {
    private final Logger log = LoggerFactory.getLogger(PictureController.class);

    @Resource
    private PictureService pictureService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private GoodsPictureRelService goodsPictureRelService;

    @Value("${picture.root.path}")
    private String UPLOADED_FOLDER;

    @PostMapping("/add")
    public Result add(@RequestParam MultipartFile file, @RequestParam String goodsNumber) throws Exception {
        Picture picture = new Picture();
        GoodsPictureRel goodsPictureRel = new GoodsPictureRel();
        Goods goods = goodsService.findBy("goodsNumber", goodsNumber);

        String name = file.getOriginalFilename();
        String ext = name.substring(name.lastIndexOf("."));
        String md5 = createMd5(file).toString();
        Picture pic = pictureService.findBy("fileHash", md5);
        if (pic != null){
            if (goods != null) {
                goodsPictureRel.setGoodsId(goods.getGoodsId());
                goodsPictureRel.setPictureId(pic.getPictureId());
                goodsPictureRelService.save(goodsPictureRel);
            }
            return ResultGenerator.genSuccessResult("图片已经存在");
        }
        String saveResult;
        if (ext.toLowerCase().equals(".jpg")|ext.toLowerCase().equals(".png")|ext.toLowerCase().equals(".jpeg")|ext.toLowerCase().equals("gif")|ext.toLowerCase().equals("bmp")) {
           saveResult = saveFile(file, md5);
        } else {
            return ResultGenerator.genFailResult("非允许的图片格式");
        }

        picture.setFileHash(md5);
        picture.setPictureName(name);
        picture.setPicturePath("goods/" + md5 + "." + ext);
        pictureService.save(picture);
        pic = pictureService.findBy("fileHash", md5);
        if (goods != null) {
            goodsPictureRel.setPictureId(pic.getPictureId());
            goodsPictureRel.setGoodsId(goods.getGoodsId());
            goodsPictureRelService.save(goodsPictureRel);
        }

        return ResultGenerator.genSuccessResult(saveResult);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        pictureService.deleteById(id);
        return ResultGenerator.genSuccessResult();
    }

    @PutMapping
    public Result update(@RequestBody Picture picture) {
        pictureService.update(picture);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/{id}")
    public Result detail(@PathVariable Integer id) {
        Picture picture = pictureService.findById(id);
        return ResultGenerator.genSuccessResult(picture);
    }

    @GetMapping
    public Result list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<Picture> list = pictureService.findAll();
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    public StringBuilder createMd5(final MultipartFile file)
            throws Exception {
        StringBuilder sb = new StringBuilder();
//        MessageDigest md_sha = MessageDigest.getInstance("SHA-1");
//        md_sha.update(testStr.getBytes());
//        String sha1 = getFormattedText(md_sha.digest());
//        System.out.println(sha1);
        //生成MD5实例
        MessageDigest md5 = MessageDigest.getInstance("SHA-1");
        InputStream inputStream = file.getInputStream();
        int available = inputStream.available();
        byte[] bytes = new byte[available];
        md5.update(bytes);
        for (byte by : md5.digest()) {
            //将生成的字节MD5值转换成字符串
            sb.append(String.format("%02X", by));
        }
        return sb;
    }

    public String saveFile(MultipartFile file, String fileHash) {
        String fileName = null;
        if (!file.isEmpty()) {
            try {
//                String fileHash = createMd5(file).toString();
                fileName = file.getOriginalFilename();
                String ext = fileName.substring(fileName.lastIndexOf("."));
                fileName = fileHash + ext;
                byte[] bytes = file.getBytes();
                BufferedOutputStream buffStream =
                        new BufferedOutputStream(new FileOutputStream(new File(UPLOADED_FOLDER + "/" + fileName)));
                buffStream.write(bytes);
                buffStream.close();
                return fileName;
            } catch (Exception e) {
                return "上传图片失败： " + fileName + ": " + e.getMessage();
            }
        } else {
            return "上传图片为空";
        }
    }

}
